<template>
  <div>
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { importEmployees } from '@/api/employees'
export default {
  data() {
    return {}
  },
  methods: {
    async handleSuccess({ results, header }) {
      const obj = {
        入职日期: 'timeOfEntry',
        姓名: 'username',
        工号: 'workNumber',
        手机号: 'mobile',
        转正日期: 'correctionTime'
      }
      // console.log(results)
      // console.log(header)
      // 定义一个空数组;
      const arr = []
      function excel_time_to_timestamp(excelTime) {
        const second = 25569
        const day_timestamp = 24 * 60 * 60 * 1000
        var dt = new Date((+excelTime - second) * day_timestamp)
        return (
          dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate()
        )
      }
      // 对数字便利，item中的key是中文
      results.forEach((item) => {
        const obj1 = {}
        for (const key in item) {
          if (key === '入职日期' || key === '转正日期') {
            obj1[obj[key]] = excel_time_to_timestamp(item[key])
          } else {
            obj1[obj[key]] = item[key]
          }
        }
        arr.push(obj1)
      })
      await importEmployees(arr)
      this.$message.success('导入成功')
      this.$router.push('/employees')
      // console.log(arr)
    },
    beforeUpload(file) {
      // 1Mb = 1024kb -> 1024b
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '上传的文件不能超过1MB',
        type: 'warning'
      })
      return false
    }
  }
}
</script>

<style scoped lang='scss'>
</style>
